#include "dlg_login.h"
#include "ui_dlg_login.h"
#include<QDebug>

dlg_login::dlg_login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::dlg_login)
{
    ui->setupUi(this);
    //钟汇鸿：将登录按钮的初始化逻辑转移到了构造函数
    //初始化
    ui->warningName->setText("用户名不能为空");
    ui->warningPwd->setText("密码不能为空");
    QPalette RED;
    RED.setColor(QPalette::WindowText,Qt::red);
    ui->warningName->setPalette(RED);
    ui->warningPwd->setPalette(RED);
    //默认不可见
    ui->warningName->setVisible(false);
    ui->warningPwd->setVisible(false);
    //钟汇鸿：添加了初始账号密码
    ui->EditName->setText("6666");
    ui->EditPassword->setText("6666");
}

dlg_login::~dlg_login()
{
    delete ui;
}

void dlg_login::on_btn_StuLogin_clicked()
{
    login("student");
}

void dlg_login::on_btn_TechLogin_clicked()
{
    login("teacher");
}

void dlg_login::on_btn_LoginExit_clicked()//钟汇鸿6月13日：实现退出按钮
{
    this->close();
}

void dlg_login::login(QString s)//钟汇鸿：将两个登录函数合一
{
    //钟汇鸿：将此处的初始化逻辑转移到构造函数
    //钟汇鸿：根据需要的表格进行初始化
    int name_col;
    int pwd_col;
    int id_col;
    QString login_tip;
    if(s=="student")
    {
        name_col=4;
        pwd_col=5;
        id_col=2;
        login_tip="学生登录";
    }
    else if(s=="teacher")
    {
        name_col=5;
        pwd_col=6;
        id_col=0;
        login_tip="教师登录";
    }
    else
        {
            qDebug()<<"需求的数据库错误！";
            return;
        }
    //获取输入内容
    QString user =ui->EditName->text();
    QString pwd = ui->EditPassword->text();
    ui->warningName->setVisible(user=="");
    ui->warningPwd->setVisible(pwd=="");
    if(user==""||pwd=="")
        return;
    //数据库查找账号和密码
    QString str = "select * from "+s;
    auto ptr = supsql::getinstance();
    QSqlQuery query;
    query.exec(str);
    qDebug()<<ptr->getCnt(s);
    if(ptr->getCnt(s)==0)
    {
        QMessageBox::warning(nullptr,"error","数据库为空");
        return;
    }
    while (query.next())
    {
        QString SqlName = query.value(name_col).toString();
        QString SqlPwd = query.value(pwd_col).toString();
        if(user == SqlName && pwd == SqlPwd)
        {
            QMessageBox::information(nullptr,"OK",login_tip);
            QString ID = query.value(id_col).toString();
            qDebug()<<ID;

            emit loginSucceeded(ID);//成功就进入主界面
            this->hide();
            return;
        }
    }
    QMessageBox::warning(nullptr,"Error","用户名或密码错误");
    ui->EditName->clear();
    ui->EditPassword->clear();
}
